package com.christina.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.christina.config.RabbitMQConfig;
import com.christina.service.MessageQueueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息队列服务实现类
 * 
 * @author Christina
 */
@Slf4j
@Service
public class MessageQueueServiceImpl implements MessageQueueService {

    private final RabbitTemplate rabbitTemplate;

    public MessageQueueServiceImpl(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @Override
    public void sendChatMessage(Long userId, String message) {
        try {
            JSONObject messageData = new JSONObject();
            messageData.put("userId", userId);
            messageData.put("message", message);
            messageData.put("timestamp", LocalDateTime.now());
            messageData.put("type", "CHAT");

            rabbitTemplate.convertAndSend(
                RabbitMQConfig.CHAT_EXCHANGE,
                RabbitMQConfig.CHAT_ROUTING_KEY,
                messageData
            );

            log.info("聊天消息已发送到队列，用户ID: {}", userId);
        } catch (Exception e) {
            log.error("发送聊天消息到队列失败，用户ID: {}", userId, e);
        }
    }

    @Override
    public void sendTaskMessage(Long taskId, String taskType, Object taskData) {
        try {
            Map<String, Object> messageData = new HashMap<>();
            messageData.put("taskId", taskId);
            messageData.put("taskType", taskType);
            messageData.put("taskData", taskData);
            messageData.put("timestamp", LocalDateTime.now());

            rabbitTemplate.convertAndSend(
                RabbitMQConfig.TASK_EXCHANGE,
                RabbitMQConfig.TASK_ROUTING_KEY,
                messageData
            );

            log.info("任务消息已发送到队列，任务ID: {}, 类型: {}", taskId, taskType);
        } catch (Exception e) {
            log.error("发送任务消息到队列失败，任务ID: {}", taskId, e);
        }
    }

    @Override
    public void sendNotificationMessage(Long userId, String notificationType, String content) {
        try {
            Map<String, Object> messageData = new HashMap<>();
            messageData.put("userId", userId);
            messageData.put("notificationType", notificationType);
            messageData.put("content", content);
            messageData.put("timestamp", LocalDateTime.now());

            rabbitTemplate.convertAndSend(
                RabbitMQConfig.NOTIFICATION_EXCHANGE,
                RabbitMQConfig.NOTIFICATION_ROUTING_KEY,
                messageData
            );

            log.info("通知消息已发送到队列，用户ID: {}, 类型: {}", userId, notificationType);
        } catch (Exception e) {
            log.error("发送通知消息到队列失败，用户ID: {}", userId, e);
        }
    }
}